import React, { Component } from 'react';
import { connect } from 'dva';
import Link from 'umi/link';
import { DatePicker, Select, Button, Table } from 'antd';
import moment from 'moment';
import styles from './MarketAnalysis.less';

const Option = Select.Option;

@connect(({ toolsModels }) => ({
  stockList: toolsModels.stockList,
  marginTrading: toolsModels.marginTrading,
}))
class MarketAnalysis extends Component {
  state = {
    stockCode: '',
    stockName: '',
    start_time: '',
    end_time: '',
    page_num: 1,
  };

  resetStock() {
    const loginInfo = JSON.parse(window.sessionStorage.getItem('LOGIN_INFO'));
    if (loginInfo) {
      this.setState(
        {
          stockCode: loginInfo.stock_code,
          stockName: loginInfo.stock_name,
        },
        () => {
          this.updateMarginTrading();
        }
      );
    }
  }

  updateMarginTrading() {
    const { dispatch } = this.props;
    dispatch({
      type: 'toolsModels/queryMarginTrading',
      payload: {
        page_num: this.state.page_num,
        page_size: 10,
        start_time: this.state.start_time,
        end_time: this.state.end_time,
        secu_code: this.state.stockCode,
      },
    });
  }

  componentDidMount() {
    this.setState({ loading: false });
    const { dispatch } = this.props;
    this.resetStock();
    dispatch({
      type: 'toolsModels/queryStockList',
      payload: {},
    });
  }

  render() {
    let { stockList, marginTrading } = this.props;

    const dateFormat = 'YYYY-MM-DD';
    let stockName = this.state.stockName;
    let stockCode = this.state.stockCode;
    let stockString = stockName + '(' + stockCode + ')';
    let stockListLoading = stockName === '';

    let generateStockSelect = () => {
      if (stockCode !== '') {
        return (
          <Select
            showSearch
            className={styles.tableMeta}
            value={stockString}
            optionFilterProp="children"
            loading={stockListLoading}
            onChange={handleStockChange}
          >
            {generateStockList()}
          </Select>
        );
      }
    };

    let generateStockList = () => {
      let res = [];
      if (stockList && stockList.data_list) {
        for (let i = 0; i < stockList.data_list.length; i++) {
          res.push(
            <Option key={'stocklist-' + i} value={stockList.data_list[i][0]}>
              {stockList.data_list[i][0]}
            </Option>
          );
        }
      }
      return res;
    };

    let handleStockChange = value => {
      this.setState(
        {
          stockName: value.split('(')[0],
          stockCode: value.split('(')[1].split(')')[0],
        },
        () => {
          this.updateMarginTrading();
        }
      );
    };

    const cols = [
      {
        title: '名称/证券代码',
        dataIndex: 'stock_name',
        key: 'stock_name',
        rander: (text, record) => (
          <span>
            {text}
            <br />
            {record.stock_code}
          </span>
        ),
      },
      {
        title: '交易日期',
        dataIndex: 'trading_day',
        key: 'trading_day',
      },
      {
        title: '融资余额（万元）',
        dataIndex: 'financing_balance',
        key: 'financing_balance',
      },
      {
        title: '融资买入额（万元）',
        dataIndex: 'financing_purchase',
        key: 'financing_purchase',
      },
      {
        title: '融资偿还额（万元）',
        dataIndex: 'financing_repayment',
        key: 'financing_repayment',
      },
      {
        title: '融券余量（万股）',
        dataIndex: 'margin_amount',
        key: 'margin_amount',
      },
      {
        title: '融券卖出量（万股）',
        dataIndex: 'margin_sales',
        key: 'margin_sales',
      },
      {
        title: '融券偿还量（万股）',
        dataIndex: 'margin_repayment',
        key: 'margin_repayment',
      },
      {
        title: '融券余额（万元）',
        dataIndex: 'margin_balance',
        key: 'margin_balance',
      },
    ];

    let pager = {
      defaultCurrent: 1,
      total: marginTrading.total_count,
      onChange: (page, pageSize) => {
        this.setState({ page_num: page }, () => {
          this.updateMarginTrading();
        });
      },
    };

    return (
      <div className={styles.outerWidthLim}>
        <div className={styles.breadCrumbContainer}>
          <Link to="/Tools/MarketAnalysis">
            <div className={styles.breadCrumbButton + ' ' + styles.breadCrumbButtonActive}>
              融资融券统计与查询
            </div>
          </Link>
          <Link to="/Tools/EInteraction">
            <div className={styles.breadCrumbButton}>互动易统计</div>
          </Link>
          <Link to="/Tools/WebsiteList">
            <div className={styles.breadCrumbButton}>常用网站</div>
          </Link>
        </div>
        <div className={styles.mainContentContainer}>
          <div>
            <DatePicker
              className={styles.rangePicker}
              defaultValue={moment(new Date(), dateFormat)}
              format={dateFormat}
              onChange={(date, dateString) => {
                this.setState({ start_time: dateString }, () => {
                  this.updateMarginTrading();
                });
              }}
            />
            <DatePicker
              className={styles.rangePicker}
              defaultValue={moment(new Date(), dateFormat)}
              format={dateFormat}
              onChange={(date, dateString) => {
                this.setState({ end_time: dateString }, () => {
                  this.updateMarginTrading();
                });
              }}
            />
            <div className={styles.pullRight}>
              <span className={styles.tableMeta}>
                公司简称：<font className={styles.redFont}>{stockName}</font>
              </span>
              <span className={styles.tableMeta}>
                证券代码：<font className={styles.redFont}>{stockCode}</font>
              </span>
              {generateStockSelect()}
              <Button
                className={styles.tableMeta}
                onClick={() => {
                  this.resetStock();
                }}
              >
                查看本公司
              </Button>
            </div>
          </div>
          <Table
            className={styles.bigTable}
            columns={cols}
            dataSource={marginTrading.data_list}
            pagination={pager}
          />
        </div>
      </div>
    );
  }
}

export default MarketAnalysis;
